<template>
  <div class="accounts-receivable-detail">
    <!-- 查询条件区域 -->
    <div class="search-container">
      <div class="search-row">
        <div class="search-item">
          <span class="label">日期</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY/MM/DD"
            class="date-picker"
          />
        </div>

        <div class="search-item">
          <span class="label">客户</span>
          <div class="select-wrapper">
            <el-select v-model="customer" placeholder="请选择" class="search-select">
              <el-option label="C00001 零售客户A" value="C00001" />
              <el-option label="C00002 批发客户B" value="C00002" />
              <el-option label="C00003 VIP客户C" value="C00003" />
              <el-option label="C00004 企业客户D" value="C00004" />
              <el-option label="C00005 电商客户E" value="C00005" />
            </el-select>
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </div>
        </div>

        <div class="search-item">
          <span class="label">业务员</span>
          <div class="select-wrapper">
            <el-select v-model="salesman" placeholder="请选择" class="search-select">
              <el-option label="销售-小王" value="sales001" />
              <el-option label="销售-小李" value="sales002" />
              <el-option label="销售-小张" value="sales003" />
            </el-select>
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </div>
        </div>

        <div class="search-actions">
          <el-button @click="resetSearch" class="reset-btn">重置</el-button>
          <el-button type="primary" @click="doSearch" class="query-btn">查询</el-button>
        </div>
      </div>

      <div class="search-row">
        <div class="search-item">
          <span class="label">客户类别</span>
          <el-select v-model="customerType" placeholder="请选择" class="search-select">
            <el-option label="零售客户" value="retail" />
            <el-option label="批发客户" value="wholesale" />
            <el-option label="VIP客户" value="vip" />
            <el-option label="企业客户" value="enterprise" />
          </el-select>
        </div>

        <div class="checkbox-item">
          <el-checkbox v-model="hideNoDebtCustomers" class="custom-checkbox">不显示无欠款客户</el-checkbox>
        </div>
      </div>
    </div>

    <!-- 报表标题区域 -->
    <div class="report-header">
      <div class="date-range-text">日期: {{ dateRange[0] }} 至 {{ dateRange[1] }}</div>
      <h2 class="report-title">应收账款明细表</h2>
      <div class="report-actions">
        <el-button type="primary" class="export-btn">导出</el-button>
        <el-dropdown class="print-btn">
          <el-button type="primary">
            打印
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>打印预览</el-dropdown-item>
              <el-dropdown-item>直接打印</el-dropdown-item>
              <el-dropdown-item>打印设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="processedTableData"
      border
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      class="detail-table"
      :span-method="spanMethod"
    >
      <el-table-column prop="customer" label="客户" min-width="180" />
      <el-table-column prop="salesman" label="业务员" min-width="100" />
      <el-table-column prop="billDate" label="单据日期" min-width="120" />
      <el-table-column prop="billNo" label="单据编号" min-width="120" />
      <el-table-column prop="businessType" label="业务类型" min-width="120" />
      <el-table-column prop="increaseReceivable" label="增加应收款" min-width="120" align="right" />
      <el-table-column prop="increasePrepayment" label="增加预收款" min-width="120" align="right" />
      <el-table-column prop="receivableBalance" label="应收款余额" min-width="120" align="right" />
      <el-table-column prop="remark" label="备注" min-width="100" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { 
  InfoFilled, 
  ArrowDown, 
} from '@element-plus/icons-vue';
import dayjs from 'dayjs'

// 日期范围
// const dateRange = ref(['2025/10/01', '2025/10/24']);
const dateRange = ref([
  dayjs().startOf('month').format('YYYY/MM/DD'), 
  dayjs().format('YYYY/MM/DD')                  
]);
// 查询条件
const customer = ref('');
const salesman = ref('');
const customerType = ref('');
const hideNoDebtCustomers = ref(false);

// 表头样式
const headerCellStyle = {
  backgroundColor: '#f5f7fa',
  fontWeight: 'bold',
  color: '#303133',
  textAlign: 'center'
};

// 原始表格数据
const rawTableData = ref([
  {
    customer: 'C00001 零售客户A',
    salesman: '',
    billDate: '',
    billNo: '期初余额',
    businessType: '',
    increaseReceivable: '0.00',
    increasePrepayment: '0.00',
    receivableBalance: '8,500.00',
    remark: ''
  },
  {
    customer: 'C00001 零售客户A',
    salesman: '销售-小王',
    billDate: '2025/10/05',
    billNo: 'XS20251005001',
    businessType: '销售出库',
    increaseReceivable: '3,200.00',
    increasePrepayment: '0.00',
    receivableBalance: '11,700.00',
    remark: '日常零售订单'
  },
  
  {
    customer: 'C00002 批发客户B',
    salesman: '',
    billDate: '',
    billNo: '期初余额',
    businessType: '',
    increaseReceivable: '0.00',
    increasePrepayment: '0.00',
    receivableBalance: '15,000.00',
    remark: ''
  },
  {
    customer: 'C00002 批发客户B',
    salesman: '销售-小李',
    billDate: '2025/10/08',
    billNo: 'XS20251008001',
    businessType: '批发销售',
    increaseReceivable: '7,500.00',
    increasePrepayment: '0.00',
    receivableBalance: '22,500.00',
    remark: '季度批发订单'
  },
  {
    customer: 'C00002 批发客户B',
    salesman: '销售-小李',
    billDate: '2025/10/12',
    billNo: 'SK20251012001',
    businessType: '收款单',
    increaseReceivable: '0.00',
    increasePrepayment: '5,000.00',
    receivableBalance: '17,500.00',
    remark: '部分付款'
  },
  
  {
    customer: 'C00003 VIP客户C',
    salesman: '',
    billDate: '',
    billNo: '期初余额',
    businessType: '',
    increaseReceivable: '0.00',
    increasePrepayment: '0.00',
    receivableBalance: '5,000.00',
    remark: ''
  },
  {
    customer: 'C00003 VIP客户C',
    salesman: '销售-小张',
    billDate: '2025/10/15',
    billNo: 'XS20251015001',
    businessType: 'VIP销售',
    increaseReceivable: '2,800.00',
    increasePrepayment: '0.00',
    receivableBalance: '7,800.00',
    remark: 'VIP专享订单'
  },
  {
    customer: 'C00004 企业客户D',
    salesman: '',
    billDate: '',
    billNo: '期初余额',
    businessType: '',
    increaseReceivable: '0.00',
    increasePrepayment: '0.00',
    receivableBalance: '12,000.00',
    remark: ''
  },
  {
    customer: 'C00005 电商客户E',
    salesman: '',
    billDate: '',
    billNo: '期初余额',
    businessType: '',
    increaseReceivable: '0.00',
    increasePrepayment: '0.00',
    receivableBalance: '9,800.00',
    remark: ''
  },
  {
    customer: 'C00005 电商客户E',
    salesman: '销售-小王',
    billDate: '2025/10/20',
    billNo: 'XS20251020001',
    businessType: '电商销售',
    increaseReceivable: '4,500.00',
    increasePrepayment: '0.00',
    receivableBalance: '14,300.00',
    remark: '电商平台订单'
  }
]);

// 处理表格数据，添加小计和合计行
const processedTableData = computed(() => {
  const result = [];
  const customerGroups = {};
  let totalReceivableBalance = 0;

  // 按客户分组
  rawTableData.value.forEach(item => {
    if (!customerGroups[item.customer]) {
      customerGroups[item.customer] = [];
    }
    customerGroups[item.customer].push(item);
  });

  // 为每个客户添加数据行
  Object.keys(customerGroups).forEach(customerName => {
    const items = customerGroups[customerName];
    
    // 添加客户数据行
    items.forEach((item, index) => {
      // 只在第一行显示客户名称
      const row = {...item};
      if (index > 0) {
        row.customer = ''; // 后续行不显示客户名称
      }
      result.push(row);
    });
    
    // 计算该客户的小计
    const lastItem = items[items.length - 1];
    const customerSubtotal = {
      customer: customerName, // 小计行显示客户名称
      salesman: '',
      billDate: '',
      billNo: '小计',
      businessType: '',
      increaseReceivable: sumColumn(items, 'increaseReceivable'),
      increasePrepayment: sumColumn(items, 'increasePrepayment'),
      receivableBalance: lastItem.receivableBalance,
      remark: '',
      isSummary: true,
      isSubtotal: true
    };
    
    result.push(customerSubtotal);
    totalReceivableBalance += parseFloat(lastItem.receivableBalance.replace(/,/g, ''));
  });

  // 添加合计行
  const totalRow = {
    customer: '',
    salesman: '',
    billDate: '',
    billNo: '合计',
    businessType: '',
    increaseReceivable: sumColumn(rawTableData.value, 'increaseReceivable'),
    increasePrepayment: sumColumn(rawTableData.value, 'increasePrepayment'),
    receivableBalance: totalReceivableBalance.toLocaleString('zh-CN', {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }),
    remark: '',
    isSummary: true,
    isTotal: true
  };
  
  result.push(totalRow);
  
  return result;
});

const spanMethod = ({ row, rowIndex, columnIndex }) => {
  if (columnIndex === 0) { // 客户列
    if (row.isSubtotal || row.isTotal) {
      // 小计和合计行不合并
      return {
        rowspan: 1,
        colspan: 1
      };
    }
    
    if (row.customer) {
      // 计算相同客户的行数（包括所有数据行，不包括小计行）
      const customerName = row.customer;
      let rowspan = 1;
      let foundSubtotal = false;
      
      // 查找后续行中属于同一客户的所有数据行
      for (let i = rowIndex + 1; i < processedTableData.value.length; i++) {
        const currentRow = processedTableData.value[i];
        
        // 如果遇到小计行，停止计数
        if (currentRow.isSubtotal) {
          foundSubtotal = true;
          break;
        }
        
        // 如果是同一客户的行或空白客户行（属于同一客户组）
        if (currentRow.customer === customerName || currentRow.customer === '') {
          rowspan++;
        } else {
          break;
        }
      }
      
      // 确保只有找到小计行时才应用合并（防止越界）
      if (foundSubtotal) {
        return {
          rowspan: rowspan,
          colspan: 1
        };
      }
    }
    
    // 非第一行的客户列不显示
    return {
      rowspan: 0,
      colspan: 0
    };
  }
  
  // 其他列保持默认
  return { rowspan: 1, colspan: 1 };
};

// 辅助函数：计算列总和
const sumColumn = (items, column) => {
  const sum = items.reduce((total, item) => {
    const value = parseFloat(item[column].replace(/,/g, '')) || 0;
    return total + value;
  }, 0);
  
  return sum.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 单元格样式
const cellStyle = ({ row }) => {
  // 小计行样式
  if (row.isSubtotal) {
    return {
      backgroundColor: '#f0f7ff',
      fontWeight: 'bold'
    };
  }
  // 合计行样式
  if (row.isTotal) {
    return {
      backgroundColor: '#fff8e6',
      fontWeight: 'bold'
    };
  }
  // 期初余额行样式
  if (row.billNo === '期初余额') {
    return {
      backgroundColor: '#f9f9f9'
    };
  }
  return ;
};

// 查询操作
const doSearch = () => {
  // 这里实现查询逻辑
  console.log('查询条件:', {
    dateRange: dateRange.value,
    customer: customer.value,
    salesman: salesman.value,
    customerType: customerType.value,
    hideNoDebtCustomers: hideNoDebtCustomers.value
  });
  // 实际项目中这里应该调用API获取数据
};

// 重置查询条件
const resetSearch = () => {
  dateRange.value = ['2025/10/01', '2025/10/24'];
  customer.value = '';
  salesman.value = '';
  customerType.value = '';
  hideNoDebtCustomers.value = false;
};
</script>

<style scoped>
/* 基础样式 */
.accounts-receivable-detail {
  padding: 15px;
  background-color: #fff;
  min-height: 100vh;
}

/* 查询区域样式 */
.search-container {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  width: 90px;
  text-align: right;
  margin-right: 10px;
  color: #606266;
}

.date-picker {
  width: 320px;
}

.select-wrapper {
  position: relative;
}

.search-select {
  width: 150px;
}

.info-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: help;
  z-index: 1;
}

.search-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.reset-btn {
  color: #606266;
  background-color: #fff;
  border: 1px solid #dcdfe6;
}

.query-btn {
  background-color: #409eff;
}

.checkbox-item {
  margin-left: 80px;
  display: flex;
  align-items: center;
}

/* 报表标题区域 */
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.date-range-text {
  color: #606266;
  font-size: 14px;
}

.report-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.report-actions {
  display: flex;
  gap: 10px;
}

.export-btn {
  background-color: #1890ff;
}

.print-btn {
  background-color: #409eff;
}


:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
/* 表格样式 */
.detail-table {
  width: 100%;
  margin-bottom: 15px;
}

/* 金额列样式 */
:deep(.el-table .cell.right-align) {
  text-align: right;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #ddd;
  border-radius:3px;
}
</style>